
<template>
  <div class="icons-container">
    <p class="warn-content m-0">
      <span class="header">品类墙</span>
    </p>
    <div class="icons-wrapper">
      <el-row>
        <el-card v-for="item in categoryList" :key="item.categoryId" class="box-card mt-20 ">
          <div slot="header" class="clearfix">
            <el-row>
              <el-col :span="12">
                <span>{{ item.categoryName }}</span>
              </el-col>
              <el-col :span="12" class="text-right">
                <el-tooltip class="item" effect="dark" content="添加品类" placement="top-end">
                  <el-button type="primary" icon="el-icon-plus" circle @click="addCategory(item)"/>
                </el-tooltip>
              </el-col>
            </el-row>
          </div>

          <template v-for="item2 in item.children">

            <el-col v-if="item2.children != null && item2.children.length >0" :span="24" :key="item2.categoryId">
              <div
                class="el-card_children children_t "
                style="display: block;width: 100%;margin-bottom: 30px;
                ">

                <el-card class="box-card mt-20" >

                  <div slot="header" class="clearfix">
                    <el-row>
                      <el-col :span="12">
                        <span>{{ item2.categoryName }}</span>
                      </el-col>
                      <el-col :span="12" class="text-right">
                        <el-tooltip class="item" effect="dark" content="添加品类" placement="top-end">
                          <el-button type="primary" icon="el-icon-plus" circle @click="addCategory(item2)"/>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="修改品类" placement="top-end">
                          <el-button type="primary" icon="el-icon-edit" circle @click="editCategory(item2,true)"/>
                        </el-tooltip>
                      </el-col>
                    </el-row>
                  </div>

                  <el-col v-for="item_3 in item2.children" :xs="8" :sm="5" :md="4" :lg="3" :key="item_3.categoryId" class="text-center mt-20" @click="handleClipboard(generateIconCode(item2),$event)">
                    <div class="icon-item" @click="editCategory(item_3)">
                      <img v-if="item_3.categoryLogoPath" slot="reference" :src="item_3.categoryLogoPath" class="logo">
                      <div v-else><i class="el-icon-upload logo"/></div>
                      <span>{{ item_3.categoryName }}</span>
                    </div>
                  </el-col>

                </el-card>

              </div>
            </el-col>

            <el-col v-if="item2.children == null || item2.children.length <=0" :xs="8" :sm="5" :md="4" :lg="3" :key="item2.categoryId" class="text-center mt-20" @click="handleClipboard(generateIconCode(item2),$event)">
              <div v-if="item2.children == null || item2.children.length <=0" class="icon-item" @click="editCategory(item2)">
                <img v-if="item2.categoryLogoPath" slot="reference" :src="item2.categoryLogoPath" class="logo">
                <div v-else><i class="el-icon-upload logo"/></div>
                <span>{{ item2.categoryName }}</span>
              </div>
            </el-col>

          </template>

        </el-card>

      </el-row>

      <el-dialog :visible.sync="categorySetDialog" width="45%">
        <el-row type="flex" justify="end" algin="middle">
          <el-col :xs="4" :md="4" class="text-right position-absolute">
            <el-tooltip class="item" effect="dark" content="保存" placement="top-end">
              <el-button type="primary" icon="el-icon-check" circle @click="saveItem(category)"/>
            </el-tooltip>
            <el-tooltip v-if="category.categoryId&&!category.isSelectParentCategoryDisabled" class="item" effect="dark" content="删除" placement="top-end">
              <el-button type="danger" icon="el-icon-delete" circle @click="deleteCategory(category)"/>
            </el-tooltip>
          </el-col>
        </el-row>
        <el-tabs v-model="activeName">
          <el-tab-pane label="网点自营品类" name="edit">
            <el-form :model="category" label-width="100px">
              <el-form-item label="品类名称" prop="categoryName">

                <el-row :gutter="10" type="flex" justify="space-between" algin="middle">
                  <el-col :xs="12" :md="12">
                    <el-input v-model.trim="category.categoryName" style="width: 178px;" placeholder="输入品类名称" />
                  </el-col>
                </el-row>

              </el-form-item>

              <el-form-item label="上级品类" prop="categoryName" >
                <el-row :gutter="10" type="flex" justify="space-between" algin="middle">
                  <el-select v-model="selectAddNetworkParentCategoryId" :disabled ="category.isSelectParentCategoryDisabled" placeholder="请选择">
                    <el-option
                      v-for="item in networkSelfOperatedCategoryList"
                      :key="item.categoryId"
                      :label="item.categoryName"
                      :value="item.categoryId"
                    />
                  </el-select>
                </el-row>
              </el-form-item>

              <el-form-item label="品类logo" prop="logo">
                <el-upload
                  ref="uploadImage"
                  :auto-upload="false"
                  :show-file-list="false"
                  :file-list="imageFileList"
                  :on-change="logoChange"
                  :on-remove="logoRemove"
                  action="string"
                  class="avatar-uploader">
                  <img v-if="dialogImageUrl" :src="dialogImageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"/>
                </el-upload>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-dialog>

      <el-dialog :visible.sync="categorySystemSetDialog" width="45%">
        <el-row type="flex" justify="end" algin="middle">
          <el-col :xs="4" :md="4" class="text-right position-absolute">
            <el-tooltip class="item" effect="dark" content="保存" placement="top-end">
              <el-button type="primary" icon="el-icon-check" circle @click="saveSystemCategoryItems()"/>
            </el-tooltip>
          </el-col>
        </el-row>
        <el-tabs v-model="activeName">
          <el-tab-pane :label="parentName" name="edit">
            <el-form :model="category" label-width="100px">
              <template v-for="(systemCategory,index) in addSystemCategorys" >
                <el-checkbox v-model="systemCategory.isSelected" :checked="systemCategory.isSelected" :key="systemCategory.categoryId" @change="checked => updateSystemCategorys(checked,index)" >{{ systemCategory.categoryName }}</el-checkbox>
              </template>
            </el-form>
          </el-tab-pane>

        </el-tabs>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import { get, post } from '@/api/utils'
import Tinymce from '@/components/Tinymce'
import PanThumb from '@/components/PanThumb'
import MdInput from '@/components/MDinput'
import Mallki from '@/components/TextHoverEffect/Mallki'
import DropdownMenu from '@/components/Share/dropdownMenu'
import waves from '@/directive/waves/index.js' // 水波纹指令
import { networkListCategory, saveNetworkCategory, deleteCategory } from '@/api/category'

export default {
  name: 'CategoryPage',
  components: {
    PanThumb,
    MdInput,
    Mallki,
    DropdownMenu,
    Tinymce
  },
  directives: {
    waves
  },
  data() {
    return {
      demo: {
        title: ''
      },
      activeName: 'edit',
      visible: false,
      category: {},
      categoryList: [],
      imageFileList: [],
      previewVisible: false,
      categorySetDialog: false,
      categorySystemSetDialog: false,
      dialogImageUrl: '',
      previewUrl: '',
      tempItem: {},
      imageData: {},
      addCategoryDialog: false,
      content: '',
      parents: new Map(),
      addSystemCategorys: [],
      parentName: '',
      networkSelfOperatedCategoryList: [],
      networkSelfOperatedCategoryinit: { 'categoryId': 0, 'categoryName': '选择上级品类(没有则不选)' },
      selectAddNetworkParentCategoryId: null
    }
  },
  computed: {
    uploadDisabled: function() {
      return this.imageFileList.length === 0
    }
  },
  created() {
    var self = this
    self.loadCategoryList()
  },
  methods: {
    loadCategoryList() {
      var self = this
      var data = {}
      networkListCategory(data).then(
        response => {
          if (response.data.status === 'success') {
            // 保存之前展开的状态
            self.categoryList = response.data.data
            console.log(1)

            if (response.data.data && response.data.data.length > 0 && response.data.data[0].children && response.data.data[0].children.length > 0) {
              self.networkSelfOperatedCategoryList = [this.networkSelfOperatedCategoryinit, ...response.data.data[0].children]
            }
          } else {
            self.$message({
              message: '品类加载失败' + response.data.messge,
              type: 'warning'
            })
          }
        }).catch(() => {
        self.$message({
          type: 'info',
          message: '网络请求失败'
        })
      })
    },
    addCategory(item) {
      var self = this
      self.category = {}

      self.dialogImageUrl = ''
      self.imageFileList = []

      if (item.fromMaintainSiteId) {
        // console.log(item.categoryId)
        this.selectAddNetworkParentCategoryId = item.categoryId
        self.categorySetDialog = true
      } else {
        self.listCategoryByParentId(item.categoryId)
        self.categorySystemSetDialog = true
      }
    },
    editCategory(item, isSelectParentCategoryDisabled) {
      if (!item.fromMaintainSiteId) return

      var self = this
      self.category = item
      self.category.isSelectParentCategoryDisabled = !!isSelectParentCategoryDisabled
      self.category.parentCategoryId = item.categoryId
      item.categoryLogoPath && (self.dialogImageUrl = item.categoryLogoPath)

      self.imageFileList = []
      self.categorySetDialog = true
    },

    editItem(row) {
      this.tempItem = Object.assign({}, row)
      this.imageFileList = []
      if (row.categoryLogoPath) {
        this.imageFileList.push({ name: 'logo', url: row.categoryLogoPath })
      }
      this.dialogFormVisible = true
    },
    async saveItem(category) {
      // 请求添加 or 更新
      var addData = new FormData()
      addData.append('categoryId', category.categoryId ? category.categoryId : '')
      addData.append('categoryName', category.categoryName ? category.categoryName : '')
      addData.append('parentCategoryId', this.selectAddNetworkParentCategoryId ? this.selectAddNetworkParentCategoryId : '')
      addData.append('categoryLogo', this.imageFileList[0] ? this.imageFileList[0].raw : '')

      if (category) {
        saveNetworkCategory(addData).then(
          response => {
            if (response.data.status === 'success') {
              this.loadCategoryList()
              this.$message({
                type: 'success',
                message: '品类保存成功'
              })
              this.categorySetDialog = false
            } else {
              this.$message({
                message: '品类保存失败' + response.data.messge,
                type: 'warning'
              })
            }
          }).catch(() => {
          this.$message({
            type: 'info',
            message: '网络请求失败'
          })
        })
      }
    },
    logoChange(file, fileList) {
      const isLt2M = file.size / 1024 / 1024 < 1
      if (!isLt2M) {
        this.$refs.uploadImage.clearFiles()
        this.$message.error('上传头像图片大小不能超过 1M')
        return false
      }
      this.imageData = file.raw
      this.imageFileList = []
      this.imageFileList.push(file)
      if (file) {
        // console.log(file)
        this.dialogImageUrl = URL.createObjectURL(file.raw)
      }
    },

    logoRemove(file, fileList) {
      this.imageData = null
      this.imageFileList = fileList
    },

    deleteCategory(row) {
      this.$confirm('确认删除品类吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCategory(row.categoryId).then(
          response => {
            if (response.data.status === 'success') {
              this.categorySetDialog = false
              this.loadCategoryList()
            } else {
              this.$message({
                message: '操作失败' + response.data.messge,
                type: 'warning'
              })
            }
          }).catch(() => {
          this.$message({
            type: 'info',
            message: '网络请求失败'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },

    listCategoryByParentId(parentId) {
      this.addSystemCategorys = []
      this.parentName = '品类信息'
      var listCategory = this.parents.get(parentId)

      if (!listCategory || listCategory.length <= 0) {
        var data = { 'parentCategoryId': parentId }
        get('/wxh-cloud-rest/rest/', '/category/listCategoryByParentId', data).then((data) => {
          if (data && data.data && data.data.status === 'success' && data.data.data) {
            var systemCategorys = data.data.data
            this.addSystemCategorys = systemCategorys
            this.parents.set(parentId, systemCategorys)
            this.isSelected(parentId)
          }
        })
      } else {
        this.addSystemCategorys = listCategory
        this.isSelected(parentId)
      }
    },

    isSelected(parentId) {
      if (this.addSystemCategorys != null && this.addSystemCategorys.length > 0) {
        this.addSystemCategorys = this.addSystemCategorys.map((systemCategory) => {
          this.categoryList.map((category) => {
            if (category && category.categoryId === parentId) {
              this.parentName = category.categoryName ? (category.categoryName) : '品类信息'
              if (category.children && category.children.length > 0) {
                category.children.map((childrenCategory) => {
                  if (childrenCategory && systemCategory && childrenCategory.categoryId && systemCategory.categoryId === childrenCategory.categoryId) {
                    systemCategory.isSelected = true
                  }
                })
              }
            }
          })
          return systemCategory
        })
      }
    },

    updateSystemCategorys(isSelected, index) {
      this.$set(this.addSystemCategorys, index, { ...this.addSystemCategorys[index], isSelected })
    },

    saveSystemCategoryItems() {
      var data = { systemcategoryIds: '' }
      if (this.addSystemCategorys != null && this.addSystemCategorys.length > 0) {
        this.addSystemCategorys.map((systemCategory) => {
          if (systemCategory && systemCategory.isSelected) {
            data.systemcategoryIds += systemCategory.categoryId + ','
          }
          if (!data.parentCategoryId) {
            if (systemCategory.parentCategoryId) {
              data.parentCategoryId = systemCategory.parentCategoryId
            }
          }
        })
      }

      data.systemcategoryIds = data.systemcategoryIds !== '' ? data.systemcategoryIds.substring(0, data.systemcategoryIds.length - 1) : data.systemcategoryIds
      var headers = { 'Content-Type': 'application/x-www-form-urlencoded' }
      post('/wxh-cloud-rest/rest/', '/category/networkUpdataSystemCategorys', data, headers).then(data => {
        if (data && data.data && data.data.status === 'success') {
          this.loadCategoryList()
          this.categorySystemSetDialog = false
        }
      })
    }

  }
}
</script>

<style scoped>
.icons-container {
  background-color: #f0f2f5;
  padding: 30px;
  overflow: hidden;
}
.icons-wrapper {
  margin: 0 auto;
}
.icon-item {
  margin: 20px;
  height: 110px;
  text-align: center;
  width: 110px;
  float: left;
  font-size: 30px;
  color: #24292e;
  cursor: pointer;
}
span {
  display: block;
  font-size: 18px;
  margin-top: 10px;
}
.header{
  font-size: 18px;
  color: #28a082;
}
.disabled{
  pointer-events: none;
}
</style>
<style>
  .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.tinymce-content {
  min-width: 700px;
  max-width: 800px;
}
.logo {
  height: 50px;
  width: 50px;
  border-radius: 50%;
  font-size: 40px;
}
.position-absolute{
  z-index: 9;
  position: absolute;
};

.el-card .el-card_children,.children_t{
  display: block;
  margin-top: 200px;
  display: flex;
  width: 100%;
}

</style>
